﻿using System;
using System.Linq;
using XRM.Security.DataAccess.Enums;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.DataAccess.Repositories.Impl;
using XRM.Security.WebUI.Helpers;

namespace XRM.Security.WebUI.Models.Report.ReportBuilder
{
    public class OpenRequestReportBuilder : ReportBuilderBase
    {
        private readonly RequestRepository _repository;
        public OpenRequestReportBuilder(RequestRepository repository)
        {
            _repository = repository;
        }

        public override string TemplateFileName
        {
            get { return "Перечень невыполненных работ"; }
        }

        public override string Create(CreateReportModel model)
        {
            var workKinds = model.GetSelectedCheckBoxValues().ToList();
            var query = _repository.GetAll(s => (s.Status == (int)RequestStatus.InWork || s.Status == (int)RequestStatus.InPart) 
                && s.RequestWorkKinds.Any(g => g.CloseDate == null && workKinds.Contains(g.WorkKindId)));
            if (model.Value.HasValue)
            {
                query = query.Where( s => s.UserRegister.DepartmentId == model.Value );
            }
            var requests = query.Select(s => new{s.Number, s.CreateDate, DepartmentName = s.UserRegister.Department.Name, 
                s.UserRegister, s.SystemUser, WorkKinds = s.RequestWorkKinds.Where(g => g.CloseDate == null && workKinds.Contains(g.WorkKindId)).Select(g => g.WorkKind.WorkKindName)})
                .OrderBy(s => s.Number).AsEnumerable().Select( s =>
                new UnperformedRequestsReportTypeUnperformedRequest
                    {
                        Numder = s.Number.ToString(), 
                        RequestCreateDate = s.CreateDate, 
                        Department = s.DepartmentName,
                        User = s.UserRegister.FullName(),
                        Performer = s.SystemUser.FullName(),
                        WorkKind = String.Join("\r\n", s.WorkKinds)
                    } ).ToArray();
            var report = new UnperformedRequestsReportType
                {
                    CreateDate = DateTime.Now,
                    UnperformedRequest = requests
                };
            return CreateXlsxDocument( Utils.SerializeToString( report ) );
        }
    }
}